'use strict';

module.exports = () => {
  return async function (ctx, next) {
    let token = '';
    if (ctx.headers.authorization && ctx.headers.authorization.split(' ')[0] === 'Bearer') {
      token = ctx.headers.authorization.split(' ')[1];
    } else if (ctx.query.access_token) {
      token = ctx.query.access_token;
    } else if (ctx.request.body.access_token) {
      token = ctx.request.body.access_token;
    } else {
      token = ctx.request.body.access_token || ctx.request.body.accesstoken;
    }

    const user = await ctx.service.userSvc.getUserByToken(token);

    if (!user) {
      ctx.status = 401;
      ctx.body = {success: false, error_msg: '错误的用户token'};
      return;
    }

    if (user.is_block) {
      ctx.status = 403;
      ctx.body = {success: false, error_msg: '您的账户被禁用'};
      return;
    }

    ctx.request.user = user;

    await next();
  };
};
